package cn.aspart.api_logger.config;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

public class ApiLogger extends CommonsRequestLoggingFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiLogger.class);

    @Override
    protected boolean shouldLog(HttpServletRequest request) {
        return true;
    }

    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {
        LOGGER.info("{}", message);
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {
        LOGGER.info("{}", message);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        super.doFilterInternal(request, responseWrapper, filterChain);

        byte[] resBodyByte = responseWrapper.getContentAsByteArray();
        LOGGER.info("[api response] --> {}", new String(resBodyByte));

    }

}
